//
//  FindGymViewController.m
//  GYMWinners
//
//  Created by Logic Solutions on 3/11/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "FindGymViewController.h"
#import "SignCheckoutViewController.h"
#import "FindGymAnnotion.h"

#import "MapKit/MapKit.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJSON.h"
#import "MBProgressHUD.h"
#import "BaseroutAPI.h"
#import "AppDelegate.h"

@implementation FindGymViewController

@synthesize locationManager;
@synthesize  mapView;
@synthesize gymNameTextField;
@synthesize gymAddressTextField;
@synthesize anno_lat;
@synthesize anno_lon;


-(IBAction)backgroundTouched:(id)sender{
    [gymNameTextField resignFirstResponder];
    [gymAddressTextField resignFirstResponder];
}

-(IBAction)textfieldReturn:(id)sender{
    [sender resignFirstResponder];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

#pragma mark - View lifecycle

- (BOOL) validate
{
    if( [gymNameTextField.text length] < 1)
    {
        [[BaseroutAPI sharedInstance] MessageBox:@"输入错误" Message:@"请输入健身馆名称"];
        
        return NO;
    }
    
    if( [gymAddressTextField.text length] < 1 )
    {
        [[BaseroutAPI sharedInstance] MessageBox:@"输入错误" Message:@"请输入健身馆地址"];
        
        return NO;
    }
    
    return YES;
    
}

-(void) submit{

    [gymNameTextField resignFirstResponder];
    [gymAddressTextField resignFirstResponder];
    
    if([self validate] == NO)
        return;
    
    NSMutableDictionary *slist = [[NSMutableDictionary alloc] init];
    [slist setObject:gymNameTextField.text forKey:@"name"];
    [slist setObject:gymAddressTextField.text forKey:@"address"];
    [slist setObject:[[BaseroutAPI sharedInstance] zGetVarEx:@"customerid"] forKey:@"cid"];
    [slist setObject:[NSString stringWithFormat:@"%f", self.anno_lat] forKey:@"lat"];
    [slist setObject:[NSString stringWithFormat:@"%f", self.anno_lon] forKey:@"lon"];
    [self zSendServer:slist theTitle:@"请稍等" theCommand:@"/location/add"];
    
}

- (void)viewDidLoad { 
    
    [super viewDidLoad]; 
    
    //1. add submit button
    UIBarButtonItem* submitButtonItem=[[UIBarButtonItem alloc] 
                                       initWithTitle:@"提交" 
                                       style:UIBarButtonItemStyleBordered
                                       target:self 
                                       action:@selector(submit)];
    self.navigationItem.rightBarButtonItem=submitButtonItem;

    //2. add map view    
    mapView.delegate=self;
    mapView.showsUserLocation=YES;
    [mapView setZoomEnabled:YES];
    [mapView setScrollEnabled:YES];
    
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate=self; 
    locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    locationManager.distanceFilter=100.0f;
    [locationManager startUpdatingLocation];
    
    MKCoordinateSpan theSpan;  
    theSpan.latitudeDelta=0.005; 
    theSpan.longitudeDelta=0.005;
    
    MKCoordinateRegion theRegion; 
    theRegion.center=[[locationManager location] coordinate]; 
    theRegion.span=theSpan; 

    [mapView setRegion:theRegion]; 
    
    if([CLLocationManager locationServicesEnabled])
    {
        [mapView setUserTrackingMode:MKUserTrackingModeFollow animated:YES];
    }
    

    //3. add annotation
    FindGymAnnotion* gymAnno=[[FindGymAnnotion alloc] init];
    gymAnno.title=@"拖拽到健身管位置";
    gymAnno.coordinate=theRegion.center;    
    [mapView addAnnotation:gymAnno];

}

- (void)dealloc {
NSLog(@"dealloc findgum view");
    mapView.delegate = nil;
    locationManager.delegate = nil;
    mapView.showsUserLocation = NO;
    [mapView removeAnnotations:mapView.annotations];
}

- (void)viewDidUnload
{
    NSLog(@"viewDidUnload findgum view");
    self.mapView.delegate=nil;
    [self setMapView:nil];
    
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)locationManager:(CLLocationManager *)manager
	didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation{

    NSString* lat=[[NSString alloc] initWithFormat:@"%g",newLocation.coordinate.latitude];
    NSString* lng=[[NSString alloc] initWithFormat:@"%g",newLocation.coordinate.longitude];
    NSString* acc=[[NSString alloc] initWithFormat:@"%g",newLocation.horizontalAccuracy];
    NSLog(@"%@__%@__%@",lat,lng,acc);
    
    MKCoordinateSpan span;
    span.latitudeDelta=0.005;
    span.longitudeDelta=0.005;
    
    MKCoordinateRegion region;
    region.center=newLocation.coordinate;
    region.span=span;
    
    [mapView setRegion:region animated:YES];
    
}

-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    NSLog(@"==viewForAnnotation==>");

    if([annotation isKindOfClass:[FindGymAnnotion class]]){
        
        static NSString* defaultPinID=@"com.findGym.pin";
        MKPinAnnotationView* pinView=(MKPinAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
        
        if(!pinView){
            pinView=[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID];
        }
        
        pinView.annotation=annotation;
        pinView.pinColor=MKPinAnnotationColorPurple;
        pinView.canShowCallout=YES;
        pinView.draggable=YES;
        [pinView setSelected:YES animated:YES];
        
        CLLocationCoordinate2D droppedAt=annotation.coordinate;
        self.anno_lat = droppedAt.latitude;
        self.anno_lon = droppedAt.longitude;
        NSLog(@"==started at %f,%f", droppedAt.latitude, droppedAt.longitude);  

        return pinView;        
    }
    return nil;    
}

-(void) mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState{
    
    if(oldState==MKAnnotationViewDragStateDragging){
        NSLog(@"MKAnnotationViewDragStateDragging");
    }
    if(newState==MKAnnotationViewDragStateEnding){
        CLLocationCoordinate2D droppedAt=view.annotation.coordinate;
        self.anno_lat = droppedAt.latitude;
        self.anno_lon = droppedAt.longitude;
        NSLog(@"==dropped at %f,%f", droppedAt.latitude, droppedAt.longitude);        
    }
}


#pragma mark - ASIFormDataRequest delegate

- (void)requestFinished:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    if (request.responseStatusCode == 200) {
        
        NSString *responseString = [request responseString];
        NSLog(@"responseString=[%@]", responseString);   
        NSDictionary *responseDict = [responseString JSONValue];
        NSString *locationID = [NSString stringWithFormat:@"%@", [responseDict objectForKey:@"id"]];
        //NSString *status = [responseDict objectForKey:@"status"];
        
        if( [[BaseroutAPI sharedInstance] validateString:locationID] )
        {
            NSLog(@"start push");
            [[BaseroutAPI sharedInstance] zSetVar:@"locationid" theValue:[responseDict objectForKey:@"id"]];

            SignCheckoutViewController* signCheckoutViewController=[[SignCheckoutViewController alloc] init];
            [[self navigationController] pushViewController:signCheckoutViewController animated:YES];
            NSLog(@"start push done");
        
        }
        else
        {
            [[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"添加失败"]; 
            
            // Just for testing
            SignCheckoutViewController* signCheckoutViewController=[[SignCheckoutViewController alloc] init];
            [[self navigationController] pushViewController:signCheckoutViewController animated:YES];
        }
        
    } else {
        NSLog(@"Unexpected error");  
        [[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"通讯失败"];
    }
    
}

- (void)requestFailed:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    NSError *error = [request error];
    NSLog(@"Error=%@", error.localizedDescription);   
    
    [[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"通讯失败"];
}

@end
